package org.sixdog.mcsit.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.sixdog.mcsit.po.Problem;
import org.sixdog.mcsit.po.User;
import org.sixdog.mcsit.service.ProblemService;
import org.sixdog.mcsit.service.TokenService;
import org.sixdog.mcsit.service.UserService;
import org.sixdog.mcsit.utils.HttpResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/seniority")
public class SeniorityController {

    @Autowired
    private ProblemService problemService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private UserService userService;


    @PostMapping("/getProblem")
    public Object getProblem(HttpServletRequest request){
        HashSet<Problem> problems = problemService.selectProblems(new Problem(), 1, 100);
        if (problems.size()==0){
            return HttpResult.build(HttpResult.ERROR_CODE,"获取失败");
        }
        Map<String,Object> resultData = new HashMap<>();
        resultData.put("size",problems.size());
        resultData.put("problems",problems);
        return HttpResult.build(HttpResult.SUCCESS_CODE,resultData,"获取成功");
    }
    @PostMapping("/markingPaper")
    public Object markingPapers(HttpServletRequest request){
        String tokenKey = request.getHeader("mcsittoken");
        List<Problem> paper = JSON.parseObject(request.getParameter("paper"),new TypeReference<ArrayList<Problem>>(){});
        if (paper==null || paper.size()==0) return HttpResult.build(HttpResult.ERROR_CODE,"阅卷失败,请重新提交");
        int scoring = problemService.scoring(paper);
        Map<String,Object> resultData = new HashMap<>();
        resultData.put("score",scoring);
        String uid = tokenService.getTokenValue(tokenKey);
        System.out.println("用户"+uid+"参与答题，得分为:"+scoring);
        if (scoring>=15){
            User user = new User();
            user.setUid(uid);
            user.setPower(1);
            userService.updateUser(user);
            return HttpResult.build(HttpResult.SUCCESS_CODE,resultData,"及格,已加入白名单");
        }
        return HttpResult.build(HttpResult.UNAUTHORIZED,resultData,"不及格");
    }
}
